package com.moyu.shopapp.service.impl;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moyu.shopapp.entity.Order;
import com.moyu.shopapp.entity.OrderItem;
import com.moyu.shopapp.entity.User;
import com.moyu.shopapp.entity.vo.CartGoodsVO;
import com.moyu.shopapp.mapper.OrderItemMapper;
import com.moyu.shopapp.mapper.UserMapper;
import com.moyu.shopapp.service.*;
import com.moyu.shopapp.mapper.OrderMapper;
import com.moyu.shopapp.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
* @author ZJF
* @description 针对表【order】的数据库操作Service实现
* @createDate 2023-12-01 16:32:18
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService{
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private CartService cartService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderItemMapper orderItemMapper;

    /**
     * 添加订单
     * @param token 用户token
     * @param totalPrice 总价
     * @param cartGoodsVOList 购物车列表
     * @return
     */
    @Override
    public String addOrder(String token, double totalPrice,List<CartGoodsVO> cartGoodsVOList) {
        //判断用户是否登录
        if (token==""||JwtUtils.isJwtExpired(token)) {
            return "用户未登录";
        }
        //检查是否有足够的库存
        for (CartGoodsVO cartGoodsVO:cartGoodsVOList){
            if (!goodsService.checkStock(cartGoodsVO.getGoodsId(),cartGoodsVO.getQuantity())){
                return "库存不足";
            }
        }
        //根据token获取用户信息
        User userInfo = userService.getUserInfo(token);
        //获取用户id
        int userId = userInfo.getUserId();

        //生成order对象并赋值
        Order order = new Order();
        order.setUserId(userId);
        order.setTotalPrice(totalPrice);
        order.setPaymentStatus("fail");
        //新建订单
        orderMapper.insert(order);
        //根据返回的订单id新建订单项
        orderItemService.addOrderItem(cartGoodsVOList,order.getOrderId());
        //删除购物车对应项
        cartGoodsVOList.forEach(item->{
            cartService.removeById(item.getCartId());
        });
        //修改货物的库存和销量
        cartGoodsVOList.forEach(item->{
            goodsService.updateStockAndSales(item.getGoodsId(),item.getQuantity(),true);
        });
        return order.getOrderId().toString();
    }

    /**
     * 获取用户订单列表
     * @param token 用户token
     * @return
     */
    @Override
    public List<Order> getOrderByUserId(String token) {
        if (token==""||JwtUtils.isJwtExpired(token)) {
            return null;
        }
        //根据token获取用户信息
        User userInfo = userService.getUserInfo(token);
        //获取用户id
        int userId = userInfo.getUserId();
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId,userId);
        return orderMapper.selectList(wrapper);
    }

    /**
     * 取消订单
     * @param token 用户token
     * @param orderId 订单id
     * @return
     */
    @Override
    public String cancelOrder(String token, int orderId) {
        //判断用户是否登录
        if (token==""||JwtUtils.isJwtExpired(token)) {
            return "用户未登录";
        }
        LambdaQueryWrapper<OrderItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderItem::getOrderId,orderId);
        List<OrderItem> orderItems = orderItemMapper.selectList(wrapper);
        //遍历每一个货物更新货物库存和销量
        orderItems.forEach(orderItem -> {
            goodsService.updateStockAndSales(orderItem.getGoodsId(),orderItem.getQuantity(),false);
        });
        orderMapper.deleteById(orderId);

        return "取消订单";
    }

    @Override
    public String updateOrderStatus(int orderId) {
        try {
            AlipayTradeQueryResponse response = Factory.Payment.Common().query(String.valueOf(orderId));
            if (response != null && response.getTradeStatus().equals("TRADE_SUCCESS")) {
                //支付成功
                LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(Order::getPaymentStatus,"success")
                        .eq(Order::getOrderId,orderId);
                orderMapper.update(null,updateWrapper);
            }else {
                //支付未成功
                return "success";
            }
        }catch (Exception e){
            return "Payment not successful";
        }
        return "success";
    }
}




